﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.IO;
using System.Net;
using System.Collections.Concurrent;

using ERPStore.Extensions;
using ERPStore.Tasks.Extensions;

namespace ERPStore.Tasks.Controllers
{
	public class TasksApiController : ApiController
	{
		public TasksApiController(ERPStore.Tasks.Services.ScheduledTaskService taskService)
		{
			this.ScheduledTaskService = taskService;
		}

		protected ERPStore.Tasks.Services.ScheduledTaskService ScheduledTaskService { get; private set; }

		[System.Web.Http.HttpGet]
		[System.Web.Http.HttpPost]
		public DateTime Ping()
		{
			return DateTime.Now;
		}

		[System.Web.Http.HttpGet]
		public virtual IQueryable<ERPStore.Tasks.ViewModels.Task> GetList()
		{
			Request.Authenticate();

			var taskList = ScheduledTaskService.GetList();
			var result = new List<ERPStore.Tasks.ViewModels.Task>();
			foreach (var item in taskList)
			{
				var task = new ERPStore.Tasks.ViewModels.Task()
				{
					Name = item.Name,
					CreationDate = item.CreationDate,
					IsRunning = item.IsRunning,
					NextRunningDate = item.NextRunningDate,
					Period = item.Period,
					StartedCount = item.StartedCount,
					Interval = item.Interval,
					Id = item.Id.ToString(),
					Runnable = ScheduledTaskService.CanRun(DateTime.Now, item),
					ApplicationName = GlobalConfiguration.Configuration.Settings.ApplicationName,
					Context = GlobalConfiguration.Configuration.ExecutingContext.ToString(),
					HostName = GlobalConfiguration.Configuration.HosterName,
					MachineName = System.Environment.MachineName,
				};
				result.Add(task);
			}
			return result.AsQueryable();
		}

		[System.Web.Http.HttpGet]
		public virtual void ForceTask(string id)
		{
			Request.Authenticate();
			ScheduledTaskService.ForceTask(id);
			Services.TasksConnection.PushMessage(string.Format("cmd|taskforced:{0},machineName:{1},hostName:{2}", id, System.Environment.MachineName, GlobalConfiguration.Configuration.HosterName));
		}

		[System.Web.Http.HttpGet]
		public virtual ERPStore.Tasks.Models.Settings GetSettings()
		{
			Request.Authenticate();
			return ScheduledTaskService.Settings;
		}

		[System.Web.Http.HttpPost]
		public virtual void ApplySettings(ERPStore.Tasks.Models.Settings settings)
		{
			Request.Authenticate();
			ScheduledTaskService.Settings = settings;
		}

	}
}